package cate.game.role.mall;

import cate.common.table.d.GDMall;
import cate.common.table.mall.row.MallBaseRow;
import cate.common.table.mall.row.MallItemsRow;
import cate.common.table.mall.row.TreasureHouseItemRow;
import cate.common.table.role.vip.RoleVipRow;
import cate.common.util.random.RWList;
import cate.game.role.Role;
import cate.game.role.mall.msg.RefreshMallResp;
import cate.game.role.mall.refresh.AllRefresh;
import com.fasterxml.jackson.annotation.JsonIgnore;
import easy.java.dev.note.NoteField;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.annotation.Transient;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Mall extends AllRefresh {
    @NoteField(value = "商店ID")
    public int id;

    @NoteField(value = "商品列表")
    public List<MallItem> itemList;

    @NoteField("主动刷新")
    @JsonIgnore
    private boolean initiativeRefresh;

    public Mall(){

    }

    public Mall(Role role, int mallId) {
        this.role = role;
        this.id = mallId;
        this.itemList = new ArrayList<>();
        // 首先尝试获取默认的商品列表
        List<MallItemsRow> rowList = role.getGame().table.mall.item.getMallItemList(id, GDMall.ItemType.T1);
        if (!rowList.isEmpty()) {
            for (MallItemsRow row : rowList) {
                itemList.add(new MallItem(role,row.id));
            }
        } else {
            // 没有的话就正常随机抽取
            refreshItems();
        }
    }

    @Override
    public void initialize(Role role) {
        super.initialize(role);
        if (itemList == null) {
            itemList = new ArrayList<>();
        }
        itemList.forEach(e -> e.initialize(role));
        checkItemList();
    }

    @JsonIgnore
    public MallBaseRow getRow() {
        return role.getGame().table.mall.base.get(id);
    }

    @JsonIgnore
    @Transient
    private List<MallItemsRow> itemsRows;

    @JsonIgnore
    private List<MallItemsRow> getItemsRows() {
        if (itemsRows == null) {
            itemsRows = role.getGame().table.mall.item.getMallItemList(id);
        }
        return itemsRows;
    }

    public void payTimesChange(int oldVip, int newVip){
        if(newVip > oldVip){
            RoleVipRow newRow = role.getGame().table.vip.base.getByLevel(newVip);
            if(newRow != null){
                RoleVipRow oldRow = role.getGame().table.vip.base.getByLevel(oldVip);
                int addTimes = newRow.mallRefreshTimes - (oldRow == null ? 0 : oldRow.mallRefreshTimes);
                addPayTimes(addTimes);
            }
        }
    }

    public void onDaySpan() {
        if (id == GDMall.TREASHURE_SHOP_ID && initiativeRefresh) {
            refreshItems();
        }
        // 检查商店的刷新周期
        checkRefreshTime();
        // 检查单个商品的刷新周期
        for (MallItem item : itemList) {
            item.onDaySpan();
        }
    }

    /** 检查商品列表 */
    private void checkItemList() {
        // 判断商店展示的商品数量是否变化（针对商品数量固定的情况）
        if (getRow().itemNum > 0 && getRow().itemNum != itemList.size()) {
            refreshItems();
            return;
        }
        // 判断商店展示的商品数量是否变化（针对商品数量不固定的情况）
        if (getRow().itemNum <= 0 && itemList.size() != getItemsRows().size()) {
            refreshItems();
            return;
        }
        // 判断商品是否存在
        for (MallItem item : itemList) {
            if (item.getRow() == null) {
                refreshItems();
                return;
            } else {
                // 对商品进行初始化
                item.initialize(role);
            }
        }
    }

    /** 刷新商品列表 */
    public void refreshItems() {
        initiativeRefresh = true;
        itemList.clear();
        List<MallItemsRow> rowList = new ArrayList<>();
        // 判断是否要随机
        if (getRow().groups != null && !getRow().groups.isEmpty()) {
            List<MallItemsRow> temp;
            RWList<MallItemsRow> rwList;
            for (MallBaseRow.itemGroup group : getRow().groups) {
                if (id == GDMall.TREASHURE_SHOP_ID) {
                    // 加入动态配置的商品
                    List<TreasureHouseItemRow> treasureItemRows = getTreasureItem();
                    for (int i = 0; i < group.num; i++) {
                        rowList.add(role.getGame().table.mall.item.get(new RWList<>(treasureItemRows).setup().get().itemId));
                    }
                } else {
                    // 基础的商品池
                    temp = getItemsRows().stream().filter(a -> a.group == group.groupId).collect(Collectors.toList());
                    rwList = new RWList<>();
                    rwList.setup(temp);
                    for (int i = 0; i < group.num; i++) {
                        rowList.add(rwList.get());
                    }
                }
            }
        } else {
            rowList.addAll(role.getGame().table.mall.item.getMallItemList(id));
        }

        for (MallItemsRow row : rowList) {
            itemList.add(new MallItem(role,row.id));
        }
    }

    /** 加入动态的商品列表 */
    private List<TreasureHouseItemRow> getTreasureItem() {
        return getItemsByMaster(role);
    }

    /** 根据主角信息获取动态商品 */
    @JsonIgnore
    public List<TreasureHouseItemRow> getItemsByMaster(Role role) {
        List<TreasureHouseItemRow> result = new ArrayList<>();
        int level = role.getBase().level;
        for (TreasureHouseItemRow row : role.getGame().table.mall.treasure.list) {
            if (row.levelMin >= 0 && level < row.levelMin) {
                continue;
            }
            if (row.levelMax >= 0 && level > row.levelMax) {
                continue;
            }
            int openday = role.getGame().getOpenDay();
            if (openday < row.opendayMin || openday > row.opendayMax) {
                continue;
            }
            result.add(row);
        }
        return result;
    }

    /** 获取商店中的一个商品 */
    @JsonIgnore
    public MallItem getItem(String idHex) {
        for (MallItem item : itemList) {
            if (StringUtils.equals(item.uid, idHex)) {
                return item;
            }
        }
        return null;
    }

    /** 检查商店的各种刷新时间 */
    @JsonIgnore
    @Override
    public void checkRefreshTime() {
        // 限购重置周期检测
        if (super.checkAutoCycle(role.getGame())) {
            this.refreshItems();
        }
        // 免费刷新周期检测
        super.checkFreeCycle();
        // 有偿刷新周期检测
        super.checkPayCycle(role.getGame());
    }

    @Override
    public String getAutoCycle() {
        return getRow().autoCycle;
    }

    @Override
    public String getFreeCycle() {
        return getRow().freeCycle;
    }

    @Override
    public int getFreeTimeMax() {
        return getRow().freeTimeMax;
    }

    @Override
    public String getPayCycle() {
        return getRow().payCycle;
    }

    @Override
    @JsonIgnore
    public int getPayTimeMax() {
        if(id == GDMall.TREASHURE_SHOP_ID){
            RoleVipRow vipRow = role.getGame().table.vip.base.getByLevel(role.getBase().vip);
            if(vipRow != null){
                return vipRow.mallRefreshTimes;
            }
        }
        return getRow().payTimeMax;
    }

    /** 通知前端商店信息变更 */
    public void noticeUpdate() {
        role.sendNow(new RefreshMallResp(this));
    }

    @Override
    public String toString() {
        return "MallPO{" + "id=" + id + ", itemList=" + itemList + '}';
    }
}
